﻿// owner 蒋家伟

#pragma once
#include <algorithm>
#include <type_traits>
#include "WeakPtr.h"
#include "IHandler.h"
#include "IArgs.h"
#include "IEvent.h"

namespace jsdk
{
    template<typename Sender, typename Args, typename Handler>
    class Event : public Sender
    {
        static_assert(std::is_base_of<IHandler, Handler>::value, "Handler need inhert from IHandler");
        static_assert(std::is_base_of<IArgs, Args>::value, "Args need inhert from IArgs");
        static_assert(std::is_base_of<IEvent, Sender>::value, "Sender need inhert from IEvent");

    public:
        virtual ~Event() {}
        virtual bool registerHandler(IHandler* pHandler) final override
        {
            if (pHandler == nullptr)
                return false;

           auto iter = std::find_if(m_handlerLists.begin(), m_handlerLists.end(), [pHandler](const WeakPtr<IHandler>& wpHandler) {
               return wpHandler.get() == pHandler;
           });

           if (iter != m_handlerLists.end())
               return false;

            m_handlerLists.push_back(pHandler);
            return true;
        }

        virtual bool unRegisterHandler(IHandler* pHandler) final override
        {
            if (pHandler == nullptr)
                return false;

            auto iter = std::find_if(m_handlerLists.begin(), m_handlerLists.end(), [pHandler](const WeakPtr<IHandler>& wpHandler) {
                return wpHandler.get() == pHandler;
            });

            if (iter != m_handlerLists.end())
            {
                m_handlerLists.erase(iter);
                return true;
            }

            return false;
        }

        virtual void sendEvent(const IArgs* pArgs) final override
        {
            for (auto& iter : m_handlerLists)
            {
                if(!iter.isValid())
                    continue;
                iter->On(pArgs);
            }
        }
    private:
        std::list<WeakPtr<IHandler>> m_handlerLists;
    };
}